package com.cweb.admin.configuration.database;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * 动态数据源配置
 */
@Configuration
@EnableTransactionManagement
public class DataSourceConfigurer {
    @Autowired
    private DataSourceProperties dataSourceProperties;

    /**
     * 动态数据库bean对象
     */
    @Bean("dynamicDataSource")
    public DataSource dynamicDataSource() {
        DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();
        // 尝试从配置文件中建立数据库连接
        DataSource dataSource = DataSourceUtil.initDataSource(dataSourceProperties);
        if (null != dataSource) {
            // 数据库配置
            DynamicDataSourceContextHolder.addMonitor("master", dataSource);
        }
        // 设置默认数据源（主库）
        dynamicRoutingDataSource.setDefaultTargetDataSource(dataSource);
        // 设置数据源map
        dynamicRoutingDataSource.setTargetDataSources(DynamicDataSourceContextHolder.getDataSourceDTOS());
        return dynamicRoutingDataSource;
    }
}

